package com.education.seckill.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.education.seckill.entity.SeckillGood;
import com.education.seckill.mapper.SeckillGoodMapper;
import com.education.seckill.service.ISeckillGoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mr.Tang
 * @since 2022-06-20
 */
@Service
public class SeckillGoodServiceImpl extends ServiceImpl<SeckillGoodMapper, SeckillGood> implements ISeckillGoodService {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     *
     * 获取时间差
     *
     * */
    @Override
    public long getCountTimeDifferent(String id) {
        SeckillGood book = this.getById(id);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime gmtStartTime = book.getGmtStartTime();
        LocalDateTime gmtOverTime = book.getGmtOverTime();
        long timeDifferent = 0;




        if(now.isBefore(gmtOverTime) && now.isAfter(gmtStartTime)){
            String nowS = LocalDateTime.now().toString();
            String gmtOverTimeS = book.getGmtOverTime().toString();
            LocalDateTime parse1 = LocalDateTimeUtil.parse(nowS);
            LocalDateTime parse2 = LocalDateTimeUtil.parse(gmtOverTimeS);
            Duration between = LocalDateTimeUtil.between(parse1, parse2);
             timeDifferent = between.toSeconds();
        }

        if(now.isBefore(gmtStartTime)){
            String nowS = LocalDateTime.now().toString();
            String gmtStartTimeS = book.getGmtStartTime().toString();
            LocalDateTime parse1 = LocalDateTimeUtil.parse(nowS);
            LocalDateTime parse2 = LocalDateTimeUtil.parse(gmtStartTimeS);
            Duration between = LocalDateTimeUtil.between(parse1, parse2);
             timeDifferent = -(between.toSeconds());
        }

        if (now.isAfter(gmtOverTime)){
             timeDifferent = 0;
        }

        return timeDifferent;
    }

    /**
     *
     * 更新商品秒杀状态
     *
     * */
    @Override
    public void updateGoodStatus(String id) {
            //查询该商品状态
        SeckillGood good = this.getById(id);
        Integer sGoodStatus = good.getSGoodStatus();
        //秒杀进行中，准备结束
        if(sGoodStatus == 1){
                good.setSGoodStatus(2);
                this.updateById(good);
        }
        //秒杀还没开始，准备开始
        if(sGoodStatus == 0){
            good.setSGoodStatus(1);
            this.updateById(good);
        }

    }

    @Override
    public SeckillGood getBookMes(String id) {
        return this.getById(id);
    }
}
